/* 
   taoio.c - my IO lib

   Copyright (C) 2006 Tao Liu

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software Foundation,
   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  

   #include <termios.h>
   #include <grp.h>
   #include <pwd.h>
*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "taostr.h"

/* 
   Read until linebreak, and return an allocated string.
   Don't forget to free it while it is unused.
 */
inline
char *
readline (FILE *fp)
{
  return readtil(fp,'\n');
}

char *
readtil (FILE *fp, char d)
{
  char * buffer;
  char * s;
  char c;						/* tmp char variable */
  long i=0;
  
  s = (char *)malloc(sizeof(char)*1);
  buffer = (char *)malloc(sizeof(char)*101);
  buffer[0] = '\0';
  s[0] = '\0';
  c = fgetc(fp);
  while ( c != EOF && c != d )
	{
	  if (i < (BUFFERSIZE-1))
		{
		  buffer[i]=c;
		  i++;
		}
	  else						/* buffer full */
		{
		  buffer[i] = c;
		  buffer[++i] = '\0';
		  s = (char *)realloc(s,sizeof(char) * (strlen(s)+BUFFERSIZE+10));
		  strcat(s,buffer);
		  i = 0;		  
		}
	  c = fgetc(fp);
	}
  /* push last buffer into s */
  buffer[i] = '\0';
  s = (char *)realloc(s,sizeof(char) * (strlen(s)+BUFFERSIZE+10));
  strcat(s,buffer);
  free(buffer);
  return s;
}

/* Function: splitstr()
 * 
 * Purpose:  Split string by any character specified in string d.
 * Args:     s  - string to split.
 *           num - pointer to integar, store the number of splitted pieces.
 *           d  - a string containing delimitation characters. 
 * Return:   character array containing pointers to every string pieces.
 */                

char **
splitstr (char *s, int * num, char *d)
{
  char *a;
  char *tmp;
  int i,n;
  char ** r;

  *num = 0;
  /* cal number of blocks... a stupid method */
  tmp = (char *)strdup(s);
  a = strtok(tmp,d);
  n = 1;
  while (  (a = strtok(NULL,d)) != NULL) n++;
  *num = n;
  free(tmp);

  a = strtok(s,d);
  r = (char **)malloc(sizeof(char*)*n );
  r[0] = a; i = 0;
  while (  (a = strtok(NULL,d)) != NULL) r[++i] = a;
  return r;
}

/* int to string */
char *
int2str ( const int a )
{
  int l,i,j;
  char * sa;
  if ( a == 0 ) 
	{
	  sa = (char *) malloc (sizeof(char) * 2 );
	  sa[0] = '0', sa[1] = '\0';
	  return sa;
	}
  for ( l = 0, j = a ; j > 0 ; j = j/10) l++;
  sa = (char *) malloc (sizeof(char) * (l+1) );
  for ( i = l-1, j = a ; j > 0 ; j = j/10,i--)
	sa[i] = (char)(j%10+48);
  sa[l] = '\0';
  return sa;
}
